package de.fsujena.chat_pi.client.userInterface.GUI;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;

import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.factories.FormFactory;

import de.fsujena.chat_pi.client.Client;

import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.JPasswordField;

public class SettingsWindow extends JDialog {
	Client clientObject;

	/**
	 * 
	 */
	private static final long serialVersionUID = 7344055587805741149L;
	private final JPanel contentPanel = new JPanel();
	private JTextField textField_port;
	private final SettingsWindow thisWindow = this;
	private JTextField textField_ip;
	private JTextField textField_username;
	private JPasswordField passwordField;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
			SettingsWindow dialog = new SettingsWindow(new Client());
			dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			dialog.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the dialog.
	 */
	public SettingsWindow(Client clientObject) {
		this.clientObject = clientObject;
		//thisWindow = this;
		setBounds(100, 100, 512, 435);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(new FormLayout(new ColumnSpec[] {
				FormFactory.RELATED_GAP_COLSPEC,
				FormFactory.DEFAULT_COLSPEC,
				FormFactory.RELATED_GAP_COLSPEC,
				ColumnSpec.decode("default:grow"),},
			new RowSpec[] {
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,}));
		{
			JLabel lblPort = new JLabel("Port");
			contentPanel.add(lblPort, "2, 2, right, default");
		}
		{
			textField_port = new JTextField();
			
			PlainDocument doc = (PlainDocument) textField_port.getDocument();
			doc.setDocumentFilter(new IntFilter());
			
			try {
				doc.insertString(0, ""+clientObject.getPort(), null);
			} catch (BadLocationException e) {
				e.printStackTrace();
			}
			textField_port.setHorizontalAlignment(SwingConstants.TRAILING);
			textField_port.setToolTipText("Set the port, the server is listening on. (between 1025 and 65535, default port: 3141)");
			textField_port.setColumns(10);
			
			contentPanel.add(textField_port, "4, 2, fill, default");
		}
		{
			JLabel lblIpAddress = new JLabel("IP address");
			contentPanel.add(lblIpAddress, "2, 4, right, default");
		}
		{
			textField_ip = new JTextField();
			contentPanel.add(textField_ip, "4, 4, fill, default");
			textField_ip.setColumns(10);
			textField_ip.setText(clientObject.getIP());
		}
		{
			JLabel lblUsername = new JLabel("username");
			contentPanel.add(lblUsername, "2, 8");
		}
		{
			textField_username = new JTextField();
			contentPanel.add(textField_username, "4, 8, fill, default");
			textField_username.setColumns(10);
			textField_username.setText(clientObject.getUsername());
			
		}
		{
			JLabel lblPassword = new JLabel("password");
			contentPanel.add(lblPassword, "2, 10");
		}
		{
			passwordField = new JPasswordField();
			contentPanel.add(passwordField, "4, 10, fill, default");
			passwordField.setText(clientObject.getPassword());
		}
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				JButton saveButton = new JButton("Save");
				saveButton.setActionCommand("Save");
				saveButton.addActionListener(new SettingsSaveListener());
				buttonPane.add(saveButton);
				getRootPane().setDefaultButton(saveButton);
			}
			{
				JButton cancelButton = new JButton("Cancel");
				cancelButton.setActionCommand("Cancel");
				cancelButton.addActionListener(new SettingsCancelListener());
				buttonPane.add(cancelButton);
			}
		}
	}
	
	
	class IntFilter extends DocumentFilter {
	   @Override
	   public void insertString(FilterBypass fb, int offset, String string,
	         AttributeSet attr) throws BadLocationException {
	
	      Document doc = fb.getDocument();
	      StringBuilder sb = new StringBuilder();
	      sb.append(doc.getText(0, doc.getLength()));
	      sb.insert(offset, string);
	
	      if (test(sb.toString())) {
	         super.insertString(fb, offset, string, attr);
	      } else {
	         // warn the user and don't allow the insert
	      }
	   }
	
	   private boolean test(String text) {
	      try {
	         Integer.parseInt(text);
	         return true;
	      } catch (NumberFormatException e) {
	         return false;
	      }
	   }
	
	   @Override
	   public void replace(FilterBypass fb, int offset, int length, String text,
	         AttributeSet attrs) throws BadLocationException {
	
	      Document doc = fb.getDocument();
	      StringBuilder sb = new StringBuilder();
	      sb.append(doc.getText(0, doc.getLength()));
	      sb.replace(offset, offset + length, text);
	
	      if (test(sb.toString())) {
	         super.replace(fb, offset, length, text, attrs);
	      } else {
	         // warn the user and don't allow the insert
	      }
	
	   }
	
	   @Override
	   public void remove(FilterBypass fb, int offset, int length)
	         throws BadLocationException {
	      Document doc = fb.getDocument();
	      StringBuilder sb = new StringBuilder();
	      sb.append(doc.getText(0, doc.getLength()));
	      sb.delete(offset, offset + length);
	
	      if (test(sb.toString())) {
	         super.remove(fb, offset, length);
	      } else {
	         // warn the user and don't allow the insert
	      }
	
	   }
	}
	
	class SettingsCancelListener implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent arg0) {
			thisWindow.dispose();
		}
	}
	
	class SettingsSaveListener implements ActionListener {
		@SuppressWarnings("deprecation")
		@Override
		public void actionPerformed(ActionEvent arg0) {
			clientObject.setPort(Integer.parseInt(textField_port.getText()));
			clientObject.setIP(textField_ip.getText());
			clientObject.setUsername(textField_username.getText());
			clientObject.setPassword(passwordField.getText());
			
			thisWindow.dispose();
		}
	}

}
